package com.swf.seed.triutil.lang;

import java.net.InetAddress;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.telnet.TelnetClient;

/**
 * 网络连接工具类
 * 
 * @author shenwf106
 * @time 2014-3-22下午3:07:03
 * @TODO
 */
public class SdNetUtils {
	private static final Log logger = LogFactory.getLog(SdNetUtils.class);
	public static int defaultTimeout = 5000;

	/** 利用commons-net第三方jar，测试ip和端口的连通性
	 * 说明：
	 * 1、TelnetClient的connect方法并没有直接返回一个逻辑值，说明当前ip和port能够连接；
	 * 2、测试连通性，注意给定超时时间
	 * 3、能够连接，connect不会抛出异常信息；不能连接，connect方法会抛出异常
	 */
	public static boolean telnet(String hostname, int port) {
		boolean isConnect = false;
		try {
			TelnetClient client = new TelnetClient();
			client.setDefaultTimeout(defaultTimeout);
			client.connect(hostname,port);
			isConnect = true;
		} catch (Exception e) {
			logger.error("telent "+hostname+" "+ port + " failed!");
		}
		return isConnect;
	}
	
	public static boolean telnet(String hostname, String port) {
		int i_port;
		try {
			i_port = Integer.parseInt(port);
		} catch (Exception e) {
			return false;
		}
		return telnet(hostname, i_port);
	}
	
	
	/**
	 * 测试主机是否能够ping通
	 * @return
	 */
	public static boolean ping(String hostname) {
		boolean reachable = false;
		try {
			InetAddress address = InetAddress.getByName(hostname);
			reachable = address.isReachable(defaultTimeout);
		} catch (Exception e) {
			logger.error("ping "+hostname+" failed", e);
		}
		return reachable;
	}
	
	public static void main(String[] args) {
		System.out.println(telnet("192.168.90.254", 6610));
		System.out.println(ping("192.168.90.254"));
	}
}
